package com.qiantu.phone.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.entity.UserInfoBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.BuildConfig;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.Log;
import com.qiantu.phone.aop.Permissions;
import com.qiantu.phone.aop.SingleClick;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.glide.GlideApp;
import com.qiantu.phone.scan.ScanCodeActivity;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.utils.Constants;
import com.qiantu.phone.event.LocationEvent;
import com.qiantu.phone.manager.OBSManager;
import com.qiantu.phone.service.LocationService;
import com.qiantu.phone.ui.adapter.ListLabelAdapter;
import com.qiantu.phone.ui.dialog.BottomAvatarDialog;
import com.qiantu.phone.ui.dialog.BottomDistrictDialog;
import com.qiantu.phone.ui.dialog.BottomEditDialog;
import com.qiantu.phone.ui.dialog.BottomListDialog;
import com.qiantu.phone.ui.dialog.BottomTimeDialog;
import com.lxj.xpopup.XPopup;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;

/**
 * time   : 2021/12/22
 */
public final class InfoSupplementActivity extends AppActivity {

    @Log
    public static void start(Context context) {
        Intent intent = new Intent(context, InfoSupplementActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    private ImageView imageAvatar;
    private TextView tvNickname;
    private TextView tvGender;
    private TextView tvBirthday;
    private TextView tvDistrict;

    /** logo 缩放比例 */
    private final float mLogoScale = 0.8f;
    /** 动画时间 */
    private final int mAnimTime = 300;
    private BottomEditDialog mBottomEditDialog;
    private BottomAvatarDialog mBottomAvatarDialog;
    private BottomListDialog mBottomListDialog;
    private BottomTimeDialog mBottomTimeDialog;
    private BottomDistrictDialog mBottomDistrictDialog;
    private File createdTempFile;

    @Override
    protected int getLayoutId() {
        return R.layout.info_supplement_activity;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
//        getTitleBar().setLeftIcon(null);
        imageAvatar = findViewById(R.id.image_avatar);
        tvNickname = findViewById(R.id.tv_nickname);
        tvGender = findViewById(R.id.tv_gender);
        tvBirthday = findViewById(R.id.tv_birthday);
        tvDistrict = findViewById(R.id.tv_district);
        getLocation();
        setRandomName();
        setOnClickListener(R.id.btn_pick_image, R.id.btn_nickname, R.id.btn_gender, R.id.btn_birthday, R.id.btn_district, R.id.btn_next);
    }

//    @Permissions({ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
    public void getLocation() {
        Intent intent = new Intent(getContext(), LocationService.class);
        getContext().startService(intent);
    }

    private void onPermissionsActivityResult(int requestCode){
        if(requestCode == XXPermissions.REQUEST_CODE && XXPermissions.isGranted(getContext(), new String[]{ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})){
            getLocation();
        }
    }

    private void setRandomName(){
        String str = "";
        for (int i = 0; i < 5; i++) {
            double random = Math.random() * 36;
            if(random < 26){
                str += (char) (random + 'a');
            }else{
                str += (int)random - 26;
            }
        }
        tvNickname.setText(getString(R.string.linglu_user) + str);
    }

    @Override
    protected void initData() {
        tvBirthday.setText("1990/01/01");
        tvGender.setText(R.string.ll_man);
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_pick_image:
                showBottomAvatarDialog();
                break;
            case R.id.btn_nickname:
                showBottomEditDialog(tvNickname.getText().toString());
                break;
            case R.id.btn_gender:
                showBottomListDialog();
                break;
            case R.id.btn_birthday:
                showBottomTimeDialog();
                break;
            case R.id.btn_district:
                showBottomDistrictDialog();
                break;
            case R.id.btn_next:
                next();
                break;
        }
    }

    private void showBottomAvatarDialog() {
        if (mBottomAvatarDialog == null) {
            mBottomAvatarDialog = new BottomAvatarDialog(this);
            mBottomAvatarDialog.setDialogClickListener(new BottomAvatarDialog.DialogClickListener() {
                @Override
                public void onConfirmClick(int selected) {
                    switch (selected){
                        case 1:
                            imageAvatar.setImageDrawable(AppApplication.getInstance().getDrawable(R.mipmap.img_me_avatar_male1));
                            imageAvatar.setTag("1");
                            break;
                        case 2:
                            imageAvatar.setImageDrawable(AppApplication.getInstance().getDrawable(R.mipmap.img_me_avatar_male2));
                            imageAvatar.setTag("2");
                            break;
                        case 3:
                            imageAvatar.setImageDrawable(AppApplication.getInstance().getDrawable(R.mipmap.img_me_avatar_girl1));
                            imageAvatar.setTag("3");
                            break;
                        case 4:
                            imageAvatar.setImageDrawable(AppApplication.getInstance().getDrawable(R.mipmap.img_me_avatar_girl2));
                            imageAvatar.setTag("4");
                            break;
                    }
                }

                @Override
                public void onStartCamera() {
                    mBottomAvatarDialog.dismiss();
                    getImage(SelectImageActivity.ACTION_CAMERA);
                }

                @Override
                public void onStartGallery() {
                    mBottomAvatarDialog.dismiss();
                    getImage(SelectImageActivity.ACTION_GALLERY);
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomAvatarDialog);
        }
        mBottomAvatarDialog.show();
    }

    private void showBottomEditDialog(String text) {
        if (mBottomEditDialog == null) {
            mBottomEditDialog = new BottomEditDialog(this);
            mBottomEditDialog.setDialogClickListener(new BottomEditDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    tvNickname.setText(mBottomEditDialog.getText());
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomEditDialog);
        }
        mBottomEditDialog.setLabel(getString(R.string.nick_name_modify));
        mBottomEditDialog.setText(text);
        mBottomEditDialog.setMaxLength(Constants.NICKNAME_NAME_MAX_LENGTH);
        mBottomEditDialog.show();
    }

    private void showBottomListDialog(){
        if (mBottomListDialog == null) {
            mBottomListDialog = new BottomListDialog(this);
            mBottomListDialog.setDialogClickListener(new BottomListDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {

                }
            });
            ListLabelAdapter listLabelAdapter = new ListLabelAdapter(this);
            List<String> data = new ArrayList<>();
            data.add(getString(R.string.ll_man));
            data.add(getString(R.string.ll_woman));
            data.add(getString(R.string.ll_secret));
            listLabelAdapter.setData(data);
            listLabelAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                    tvGender.setText(listLabelAdapter.getSelected());
                    mBottomListDialog.dismiss();
                }
            });
            mBottomListDialog.setAdapter(listLabelAdapter);
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomListDialog);
        }
        ListLabelAdapter listLabelAdapter = (ListLabelAdapter) mBottomListDialog.getAdapter();
        listLabelAdapter.setSelected(tvGender.getText().toString());
        mBottomListDialog.show();
    }

    private void showBottomTimeDialog(){
        if (mBottomTimeDialog == null) {
            mBottomTimeDialog = new BottomTimeDialog(this);
            mBottomTimeDialog.setDialogClickListener(new BottomTimeDialog.DialogClickListener() {
                @Override
                public void onConfirmClick(String time) {
                    tvBirthday.setText(time);
                    mBottomTimeDialog.dismiss();
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomTimeDialog);
        }
        mBottomTimeDialog.show();
    }

    private void showBottomDistrictDialog(){
        if (mBottomDistrictDialog == null) {
            mBottomDistrictDialog = new BottomDistrictDialog(this);
            mBottomDistrictDialog.setDialogClickListener(new BottomDistrictDialog.DialogClickListener() {
                @Override
                public void onConfirmClick(String text, String code) {
                    tvDistrict.setText(text);
                    mBottomDistrictDialog.dismiss();
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomDistrictDialog);
        }
        if(!TextUtils.isEmpty(tvDistrict.getText())){
            String[] locations = tvDistrict.getText().toString().split(" ");
            if(locations.length == 3){
                mBottomDistrictDialog.setSelectedItem(locations[0], locations[1], locations[2]);
            }
        }
        mBottomDistrictDialog.show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLocationEvent(LocationEvent event) {
        tvDistrict.setText(AppApplication.getInstance().currentLocation.province + " " + AppApplication.getInstance().currentLocation.city + " " + AppApplication.getInstance().currentLocation.district);
    }


    private void next(){
        String avatarTag = imageAvatar.getTag() == null ? null : imageAvatar.getTag().toString();
        if (TextUtils.isEmpty(avatarTag)) {
            toast(R.string.please_select_avatar);
            return;
        }
        String avatar = null;
        switch (avatarTag){
            case "1":
                avatar = BuildConfig.APP_AVATAR_BASE + "img_me_avatar_male1.png";
                break;
            case "2":
                avatar = BuildConfig.APP_AVATAR_BASE + "img_me_avatar_male2.png";
                break;
            case "3":
                avatar = BuildConfig.APP_AVATAR_BASE + "img_me_avatar_girl1.png";
                break;
            case "4":
                avatar = BuildConfig.APP_AVATAR_BASE + "img_me_avatar_girl2.png";
                break;
            default:
                avatar = avatarTag;
                break;
        }
        String nickname = tvNickname.getText() == null ? null : tvNickname.getText().toString().trim();
        if (TextUtils.isEmpty(nickname)) {
            toast(R.string.please_enter_nickname);
            return;
        }
        String genderName = tvGender.getText() == null ? null : tvGender.getText().toString();
        if (TextUtils.isEmpty(genderName)) {
            toast(R.string.please_select_gender);
            return;
        }
        int gender;
        if (getString(R.string.ll_man).equals(genderName)){
            gender = 1;
        }else if (getString(R.string.ll_woman).equals(genderName)){
            gender = 2;
        }else {
            gender = 3;
        }
        String birthday = tvBirthday.getText() == null ? null : tvBirthday.getText().toString();
        if (TextUtils.isEmpty(birthday)) {
            toast(R.string.please_select_birthday);
            return;
        }
        String district = tvDistrict.getText() == null ? null : tvDistrict.getText().toString();
        if (TextUtils.isEmpty(district)) {
            toast(R.string.please_select_district);
            return;
        }
        String[] districts = district.split(" ");
        UserInfoBean userInfo = new UserInfoBean();
        userInfo.setNickName(nickname);
        userInfo.setGender(gender + "");
        userInfo.setBirthday(birthday);
        userInfo.setProvince(districts[0]);
        userInfo.setCity(districts[1]);
        userInfo.setDistrict(districts[2]);
        userInfo.setAvatar(avatar);
        // 隐藏软键盘
        hideKeyboard(getCurrentFocus());
        LLHttpManager.editBasicInfo(this, userInfo, new HttpCallback<HttpData<Void>>(this){
            @Override
            public void onStart(Call call) {
                showDialog();
            }

            @Override
            public void onEnd(Call call) {hideDialog();}

            @Override
            public void onSucceed(HttpData<Void> data) {
                if(data.isRequestSucceed()){
                    if (createdTempFile != null) {
                        createdTempFile.delete();
                    }
                    AppApplication.getInstance().getLoginInfo().setRegistrationProgress(2);
                    AppApplication.getInstance().getLoginInfo().setUserInfo(userInfo);
                    AppApplication.getInstance().updateLoginInfo(AppApplication.getInstance().getLoginInfo());
                    FamilyInfoActivity.start(InfoSupplementActivity.this);
                    finish();
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }
        });
    }

    private XXPermissions xxPermissions;
    private void getImage(String action) {
        if(xxPermissions == null){
            xxPermissions = XXPermissions.with(this);
        }
        String[] permissions = new String[]{
                Manifest.permission.CAMERA
        };

        if(AppApplication.isHuawei() && !XXPermissions.isGranted(getContext(),permissions)){
            showConfirmHintDialog("App需要使用您的照相/相册以及存储权限，来拍摄或从相册选取图片作为用户头像，并对其进行保存。如若已拒绝，再使用本功能前请先前往手机设置中将本应用的相机/相册权限改为允许。",action);
        }else{
            requestPermission(action);
        }
    }

    private void actionProfilePic(String action) {
        Intent intent = new Intent(this, SelectImageActivity.class);
        intent.setAction(SelectImageActivity.ACTION_SQUARE);
        intent.putExtra("ACTION", action);
        startActivityForResult(intent, new OnActivityCallback() {
            @Override
            public void onActivityResult(int resultCode, @Nullable Intent data) {
                if (data!=null && data.getExtras()!=null){
                    //在这里获得了剪裁后的Bitmap对象，可以用于上传
                    String imagePath = data.getExtras().getString(SelectImageActivity.CROP_IMAGE_PATH);
                    createdTempFile = new File(imagePath);
                    updateCropImage();
                }
            }
        });
    }

    /**
     * 上传裁剪后的图片
     */
    private void updateCropImage() {
        if (createdTempFile == null) return;
        showDialog();
        String path = String.format("avatar/default/avatar-%s-%d.jpg",AppApplication.getInstance().getUserPhone(),System.currentTimeMillis());
        OBSManager.updateImage(path, createdTempFile, new OBSManager.OBSCallBack() {
            @Override
            public void onSuccess(String imgUrl) {
                if (imgUrl!=null){
                    GlideApp.with(getActivity())
                            .load(createdTempFile)
                            .placeholder(imageAvatar.getDrawable())
                            .error(imageAvatar.getDrawable())
                            .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
                            .into(imageAvatar);
                    imageAvatar.setTag(imgUrl);
                    hideDialog();
                }
            }

            @Override
            public void onFail() {
                hideDialog();
            }
        });
    }

    private BaseDialog mConfirmHintDialog;
    private ConfirmHintDialog.Builder mConfirmHintDialogBuilder;

    private void showConfirmHintDialog(String text,String action) {
        if (mConfirmHintDialog == null) {
            mConfirmHintDialogBuilder = new ConfirmHintDialog.Builder(getActivity())
                    .setRightBtnText(getString(R.string.ok))
                    .setListener(new ConfirmHintDialog.OnListener() {
                        @Override
                        public void onLeftClick(BaseDialog dialog) {
                            finish();
                        }

                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            requestPermission(action);
                        }
                    });
            mConfirmHintDialog = mConfirmHintDialogBuilder.create();
        }
        mConfirmHintDialogBuilder.setCancelable(false);
//        mConfirmHintDialogBuilder.setCanceledOnTouchOutside(false);
        mConfirmHintDialogBuilder.setContent(text);
        mConfirmHintDialog.show();
    }

    private void requestPermission(String action){
        xxPermissions.permission( Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if(all){
                            actionProfilePic(action);
                        }
                    }
                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        ToastUtils.show(R.string.common_permission_fail_1);
                    }

                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        onPermissionsActivityResult(requestCode);
    }

    @Override
    public void onBackPressed() {
        Intent home = new Intent(Intent.ACTION_MAIN);
        home.addCategory(Intent.CATEGORY_HOME);
        startActivity(home);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}